package com.example.my_self_view.list2

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.util.TypedValue
import android.view.MotionEvent
import android.view.View

class LetterSideBar: View {

    private val paint by lazy { Paint() }
    private val rect by lazy { Rect() }
    private val letterList = arrayListOf("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z")
    // 当前触摸的字母
    private var currentTouchLetter: String = ""

    constructor(context: Context): this(context, null) {
    }

    constructor(context: Context, attrs: AttributeSet?): this(context, attrs, 0) {
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): this(context, attrs, defStyleAttr, 0){
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int): super(context, attrs, defStyleAttr, defStyleRes) {
        initData(attrs)
    }

    private fun initData(attrs: AttributeSet?) {
        paint.apply {
            isAntiAlias = true
            isDither = true
            textSize = sp2px(12)
            color = Color.BLUE
            textAlign = Paint.Align.CENTER
        }
    }

    private fun sp2px(sp: Int): Float{
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp.toFloat(), resources.displayMetrics)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        // 计算指定宽度 = 左右的padding + 字母的宽度
        paint.getTextBounds("A", 0, 1, rect)
        val width = rect.width() + paddingStart + paddingEnd
        // 高度可以直接获取
        val height = MeasureSpec.getSize(heightMeasureSpec)

        setMeasuredDimension(width, height)
    }

    override fun onDraw(canvas: Canvas) {
        // 画26个字母
        val dx = width/2f - rect.width()/2f
        val itemHeight = (height - paddingTop - paddingBottom) / letterList.size
        for ((i,letter) in letterList.withIndex()) {
            // 知道每个字母的中心位置 1：字母的高度一半 2：字母高度一半+前面字母的高度
            val letterCenterY = i * itemHeight + itemHeight / 2 + paddingTop
            // 基线：基于中心位置
            val fontMetrics = paint.fontMetrics
            val dy = - (fontMetrics.top + fontMetrics.bottom) / 2
            val baseLine = letterCenterY + dy

            // 当前字母 高亮
            if (letterList[i] == currentTouchLetter) {
                paint.color = Color.RED
                canvas.drawText(letter, dx, baseLine, paint)
            } else {
                paint.color = Color.BLUE
                canvas.drawText(letter, dx, baseLine, paint)
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
                // 计算出当前触摸字母
                val currentMoveY = event.y.toFloat()
                // 位置 = currentMoveY / 字母高度，通过位置获取字母
                val itemHeight = (height - paddingTop - paddingBottom) / letterList.size
                var currentPosition = (currentMoveY / itemHeight).toInt()
                if (currentPosition < 0) currentPosition = 0
                if (currentPosition > letterList.size - 1) currentPosition = letterList.size - 1
                currentTouchLetter = letterList[currentPosition]
                touchLetterListener?.touch(currentTouchLetter)
                // 重新绘制
                invalidate()
            }
            MotionEvent.ACTION_UP -> {
                touchLetterListener?.up()
            }
        }
        return true
    }

    private var touchLetterListener: TouchLetterListener? = null
    fun setTouchLetterListener(letterListener: TouchLetterListener?) {
        touchLetterListener = letterListener
    }
    interface TouchLetterListener {
        fun touch(letter: String)
        fun up()
    }
}